<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Article extends MY_Controller{

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
	public function __construct()
    {
        parent::__construct();
		$this->load->database();
		$this->load->model('art_model');	
		$this->load->helper('download');

	}
	public function index()		
	{
		$out_datas=$this->pager(3,"oa_articleclass");
		$out_datas['menu'] = $this->getMenu();
		$this->load->view('article',$out_datas);
	}

	public function articlelist()
	{		
		$res = $this->db->query("select id,title from oa_articleclass");
		$arr = $res->result_array();
		$classarr = array();
		foreach($arr as $k=>$v){
			$classarr[$v['id']]=$v['title'];
		}
		$where = '';
		
		$where = "memberids` like '%,".$this->session->userdata("userid").",%' or `userid` = ".$this->session->userdata("userid")."";
		
	
		$out_datas=$this->pager(3,"oa_articlemain",$where);
		$res_main = $this->db->query("select artids  from oa_artrelation where memberids like '%,".$this->session->userdata("userid").",%'");
		//echo $this->db->last_query();
		$main_arr = $res_main->result_array();
		$members = array();
		foreach($main_arr as $v){
			$members[] = $v['artids'];
		}
		$out_datas['class'] = $classarr;
		for($i=0;$i<count($out_datas['datas']);$i++){			
			$out_datas['datas'][$i]->artitype = $classarr[$out_datas['datas'][$i]->artitype];		
			if($members){
				if(in_array($out_datas['datas'][$i]->id,$members)){
					$out_datas['datas'][$i]->read = 1;
				}else{
					$out_datas['datas'][$i]->read = 0;
				}
			}else{
				$out_datas['datas'][$i]->read = 0;
			}
		}
		$out_datas['menu'] = $this->getMenu();
		$this->load->view('articlelist',$out_datas);	
	}
	public function pager($seq,$table,$where=null)
	{
		$this->load->model('mcom_model');
        $count=$this->mcom_model->query_count($table,$where);
		
		$this->load->library('Pager');
        $list=$this->pager->ar($count,$where,$table,$seq,10);
		
        $current=$this->uri->segment($seq);
        return array("datas"=>$list->query,'current'=>$current);
    }
	public function articlecontent($id)
	{
		
		$res = $this->db->query("select memberids from oa_artrelation where artids=".$id);
		$memberid = $res->result_array();
		$memberids = str_replace(','.$this->session->userdata("userid").',',',',$memberid[0]['memberids']);
		$this->db->query("update oa_artrelation set memberids='".$memberids."' where artids=".$id);		
		$res1 = $this->db->query("select m.title,m.content,m.intotime,m.artitype,m.id as mainid from oa_articlemain as m where id=".$id);
		$mainarr = $res1->result_array();
		$res2 = $this->db->query("select * from oa_article_".$mainarr[0]['artitype']." where mainid=".$mainarr[0]['mainid']);
		$infoarr = $res2->result_array();
		$arr = $infoarr[0];
		$arr['title'] = $mainarr[0]['title'];		
		$arr['intotime'] = $mainarr[0]['intotime'];	
		$arr['artitype'] = $mainarr[0]['artitype'];	
		$arr['mainid'] = $mainarr[0]['mainid'];	
		$arr['content'] = $mainarr[0]['content'];	
		$arr['menu'] = $this->getMenu();
		$this->load->view('articlecontent',$arr);
	}
	public  function insert()
	{
		if($this->input->post()){
			$arr = array('title'=>$this->input->post('title'));
			$num = $this->art_model->insert_typeinfo($arr);
			$this->art_model->update_typeinfo(array('tbname'=>'oa_article_'.$num), array('id'=>$num));	
			$this->index();
			
		}else{
			
			$this->load->view('articletp',array('menu'=>$this->getMenu()));
		}
	}
	public function delart()
	{	
		$this->art_model->delete_typeinfo($this->input->post('id'));		
	}
	public function delartmain()
	{	
		$this->db->query("delete from oa_articlemain where id=".$this->input->post('id'));		
	}
	public function edit()
	{	
		$this->art_model->update_typeinfo(array('title'=>$this->input->post('title')), array('id'=>$this->input->post('id')));		
	}
	public function articlefield($num)
	{
		$articlelog = $this->art_model->select_articlelog('classid in('.$num.' , 0)');				
		$this->load->view('articlefield',array('menu'=>$this->getMenu(),'log'=>$articlelog,'num'=>$num));
	}
	public function intofield($num)
	{
		$result = $this->art_model->select_datatype();
		$this->load->view('intofield',array('menu'=>$this->getMenu(),'num'=>$num,'result'=>$result));
	}
	public function insertlog()
	{
		$result = $this->db->query('select title,text,type from oa_datatype where id='.$this->input->post('datatypeid'));
		$data = $result->result_array();
		$info['classid'] = $this->input->post('classid');
		$info['formtext'] = $this->input->post('formtext');		
		$info['datatext'] = $data[0]['text'];
		$info['datatype'] = $data[0]['title'];
		$info['fieldname'] = $this->input->post('fieldname');
		$info['fieldlength'] = $this->input->post('fieldlength');
		$info['vdefault'] = $this->input->post('vdefault');
		$info['textype'] = $data[0]['type'];
		$this->db->insert('oa_articlelog',$info ); 
		$this->articlefield($this->input->post('classid'));
		
	}
	public function dellog()
	{
		$query = $this->db->delete('oa_articlelog',array('id'=>$this->input->post('id')));	
	}
	public function createtable($num)
	{
		$result = $this->db->query("show tables ");
		$table = $result->result_array();
		$return = '';
		$tbname = 'oa_article_'.$num.'';
		for($i=0;$i<count($table);$i++){
			if($table[$i]['Tables_in_weboa'] == $tbname/*'oa_articlelog'*/ ){
				$return = true;
				break;
			}else{
				$return = false;
			}
		}
		$articlelog = $this->art_model->select_articlelog('classid ='.$num.'');	
		if(!$return){
			$sql = 'CREATE TABLE `oa_article_'.$num.'` (';
			$sql .= '`id` int(11) NOT NULL AUTO_INCREMENT,';	
			$sql .= '`mainid` int(11) NOT NULL ,';	
			foreach($articlelog as $item){	
				$sql .= "`".$item->fieldname."` ".$this->get_clumntype($item->datatype,$item->fieldlength)." DEFAULT NULL COMMENT '".$item->formtext."',";
			}
			$sql .= 'PRIMARY KEY (`id`)';
			$sql .= ') ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1' ;
			//echo $sql;exit;

			$this->db->query($sql);

		}else{
			$sql = "SHOW   COLUMNS   FROM   ".$tbname; 
			$result1 = $this->db->query($sql);
			$columns = $result1->result_array();
			for($i=0;$i<count($columns);$i++){
				if($columns[$i]['Field'] != 'id'){
					$arr1[] = $columns[$i]['Field'];
				}
			}
			foreach($articlelog as $item){
				$arr2[] = $item->fieldname;
			}
			if(array_diff($arr1,$arr2)){//删除表中多余的字段
				$arr1_info = array_values(array_diff($arr1,$arr2));				
				if($arr1_info){
					for($i=0;$i<count($arr1_info);$i++){
						$sql = "alter table ".$tbname." drop column `".$arr1_info[$i]."`"; 
						$this->db->query($sql);

					}
				}
			}
			if(array_diff($arr2,$arr1)){//添加用户新创的字段				
				$arr2_info = array_values(array_diff($arr2,$arr1));	
				if($arr2_info){
					for($i=0;$i<count($arr2_info);$i++){
						$typeinfo = $this->db->query("select datatype,fieldlength from `oa_articlelog` where classid=".$num." and fieldname='".$arr2_info[$i]."'");
						$typeclumn = $typeinfo->result_array();
						$sql = "alter table ".$tbname."  add `".$arr2_info[$i]."`  ".$this->get_clumntype($typeclumn[0]['datatype'],$typeclumn[0]['fieldlength']);
						$this->db->query($sql);
					}
				}
			}
		
		}
		header("Content-Type:text/html;charset=utf-8");
		echo "<script>alert('保存成功！');window.location.href='/index.php/article/index';</script>";
	}
	public function get_clumntype($type,$length)
	{
		$last_type = '';
		if($type == 'text' || $type == 'datetime'){
			$last_type = $type;
		}else{
			$last_type = $type."(".$length.")";
		}
		return $last_type;
	}
	public function article_add($num)
	{
		$result = $this->db->query("show tables ");
		$table = $result->result_array();
		$return = '';
		$tbname = 'oa_article_'.$num.'';
		for($i=0;$i<count($table);$i++){
			if($table[$i]['Tables_in_weboa'] == $tbname/*'oa_articlelog'*/ ){
				$return = true;
				break;
			}else{
				$return = false;
			}
		}
		if(!$return){
			header("Content-Type:text/html;charset=utf-8");
			echo "<script>alert('数据表不存在，请保持字段管理！');window.location.href='/index.php/article/articlefield/".$num."';</script>";
		}
		$departre = $this->db->query("select id,name from oa_depart where pid=0 ");
		$depart = $departre->result_array();
		
		$articlelogre = $this->db->query('select * from oa_articlelog where classid ='.$num.' order by id asc');	
		$articlelog = $articlelogre->result_array();
		$columnsre = $this->db->query('show COLUMNS  FROM '.$tbname.' ');
		$column = $columnsre->result_array();
		$arrcolumn = array();
		for($i=1;$i<count($column);$i++){
			$arrcolumn[] = $column[$i]['Field'];
		}
		foreach($articlelog as $k=>$v){			
			if(!in_array($v['fieldname'],$arrcolumn)){
				unset($articlelog[$k]);
			}
		}
		$userinfore = $this->db->query("select id,departid,username from oa_user");
		$userinfo = $userinfore->result_array();		
		foreach($userinfo as $v){
			for($i=0;$i<count($depart);$i++){				
				if($depart[$i]['id'] == $v['departid']){
					$depart[$i]['member'][] = $v;
					break;
				}
			}
		}
		$this->load->view("atricle_add",array('menu'=>$this->getMenu(),'depart'=>$depart,'articlelog'=>$articlelog,'num'=>$num));
	}
	public function atricle_insert($num)
	{	
		$data1['filepath'] = '';
		$filename = $this->input->post('file_L_name');	
		if($filename){			
			$config['upload_path'] = './uploads/';
			$config['allowed_types'] = 'gif|jpg|png|txt';
			$config['max_size'] = '100';
			$config['max_width']  = '1024';
			$config['max_height']  = '768';

			$this->load->library('upload', $config);
		
			if ( ! $this->upload->do_upload($filename))
			{
				$return = array('error' => $this->upload->display_errors());

				
			} 
			else
			{
				$return = array('upload_data' => $this->upload->data());

				
			}
			if($return){
				$data1['filepath'] = './uploads/'.$return['upload_data']['file_name'];
			}

		}
		$data1['title'] = $this->input->post('title');
		$data1['memberids'] = ",".$this->input->post("memberids");
		$data1['userid'] = $this->session->userdata("userid");
		$data1['intotime'] = date("Y-m-d H:i:s",time());
		$data1['artitype'] = $num;
		$data1['content'] = $this->input->post('content');

		if($this->db->insert('oa_articlemain', $data1)){
			$tbname = 'oa_article_'.$num;
			$sql = "SHOW   COLUMNS   FROM   ".$tbname; 
			$result1 = $this->db->query($sql);
			$columns = $result1->result_array();
			for($i=0;$i<count($columns);$i++){
				if($columns[$i]['Field'] != 'id'){					
					if($columns[$i]['Field'] == $filename && $data1['filepath']!=''){
						$data2[$columns[$i]['Field']] = $data1['filepath'];
					}else{
						$data2[$columns[$i]['Field']] = $this->input->post($columns[$i]['Field']);
					}
				}
			}
						
			$data3['artids'] = $data2['mainid'] = $this->db->insert_id();		
			
			$this->db->insert('oa_article_'.$num, $data2);
		
			$data3['memberids'] = $data1['memberids'];		
			$data3['artitype'] = $num;
			$this->db->insert('oa_artrelation',$data3);
		}
		header("Content-Type:text/html;charset=utf-8");
		echo "<script>alert('保存成功！');window.location.href='/index.php/article/articlelist';</script>";

	}
	public function bulk_operations()
	{
		$allid = implode(',',$this->input->post('did'));
		$result = $this->db->query("delete from oa_articleclass where id in(".$allid.")");
		
		if($result){
			header("Content-Type:text/html;charset=utf-8");
			echo "<script>alert('删除成功！');window.location.href='/index.php/article/index';</script>";
		}


	}
	public function atricle_down($file)
	{
		$data = file_get_contents('./uploads/'.$file); // 读文件内容		

		force_download($file, $data); 

	}
	public function atricle_all_down()
	{
		$time = time().'.zip';
		$did = implode(",",$this->input->post('did'));
		$filepath = $this->db->query("select filepath from oa_articlemain where id in(".$did.") and filepath!='' ");	
		$arr = $filepath->result_array();
		$file = array();
		foreach($arr as $k=>$v){
			$file[] = $v['filepath'];
		}
		$this->create_zip($file, './uploads/'.$time,true);
		$data = file_get_contents('./uploads/'.$time); // 读文件内容	

		force_download($time, $data); 
		
	}
	public function create_zip($files = array(),$destination = '',$overwrite = false) {	
		if(file_exists($destination) && !$overwrite) { return false; }	
		$valid_files = array();
		if(is_array($files)) {
			foreach($files as $file) {			
				if(file_exists($file)) {
					
				$valid_files[] = $file;
				}
			}
		}
		if(count($valid_files)) {
			$zip = new ZipArchive();
			if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
				return false;
			}
			foreach($valid_files as $file) {
				
				$filename = explode('/',$file);//var_dump($filename);exit;
				$zip->addFile($file ,$filename[2]);
			}
			$zip->close();
			return file_exists($destination);
		}else{
			return false;
		}
	}
	public function point()
	{
		$res = $this->db->query("select *  from oa_artrelation where memberids like '%,".$this->session->userdata("userid").",%'");
		if($res->num_rows()){
			echo $res->num_rows();
		}else{
			echo 0;
		}

	}
	public function checkfieldname(){
		$num = $this->input->post("classid");
		$fieldname = $this->input->post("fieldname");
		$typeinfo = $this->db->query("select * from `oa_articlelog` where classid in(".$num.",0) and fieldname='".$fieldname."'");
		$typeclumn = $typeinfo->result_array();		
		if(!$typeclumn ){
			echo 0;
		}else{
			echo 1;
		}
	}
	/*
		header("Content-Type:text/html;charset=utf-8");
		echo "<script>alert('12');window.location.href='/index.php/Login/index';</script>";

		/*$result = $this->db->query("show tables like 'oa_article_%'");
		$arr = $result->result_array();
		for($i=0;$i<count($arr);$i++){
			$tbname = array_values($arr[$i]);
			if($tbname[0] != 'oa_articleclass' && $tbname[0] != 'oa_articlelog'){$tbarr[] = $tbname[0];}
		}
		$sql = 'CREATE TEMPORARY TABLE oa_tem_table';
		if($tbarr){
			for($i=1;$i<count($tbarr);$i++){
				$sql .= '(select id as atrid,title,artype from '.$tbarr[$i].')';
				$sql .= ' UNION ';
			}
			$sql .= '(select id as atrid,title,artype from '.$tbarr[0].')';
			
		}
		$this->db->query($sql);
		$res = $this->db->query("select * from oa_tem_table");	
		//var_dump($res->result_array());exit;
	*/
	
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */